#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "network.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QNetworkInterface>
#include <QHostAddress>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , serial(new QSerialPort)
    , timer(new QTimer)
    , W("WG"), A("AG"), S("SG"), D("DG")
    , speed(50)
    , player(new QMediaPlayer)
{

    connect(timer, &QTimer::timeout, this, &MainWindow::onTimerTimeout);


    ui->setupUi(this);

    timer->setInterval(5000);
    getLocalIPAddresses();

    tcpServer = new QTcpServer(this);
    tcpSocket = NULL;
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_SerialButton_clicked()
{
    if(!tcpServer->listen(QHostAddress::Any,ui->lineEdit->text().toInt()))
    {
        QMessageBox::critical(this, "失败", "服务器启动失败");
    }else{
        QMessageBox::information(this, "成功", "服务器启动成功");
        ui->label_2->setText("服务器已启动");
    }

    connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::newConnection_slot);
}

void MainWindow::on_SendButton_clicked()
{
    if(tcpSocket == NULL){
        return;
    }
    QString text = ui->SentEdit->toPlainText();
    tcpSocket->write(text.toUtf8());
}

void MainWindow::on_RecvClearButton_clicked()
{
    ui->RecvBrowser->clear();
}

void MainWindow::on_SendClearButton_clicked()
{
    ui->SentEdit->clear();
}

void MainWindow::keyPressEvent(QKeyEvent *event) {
    if(event->isAutoRepeat()) {
        return; // 忽略自动重复的事件
    }

    if(event->key() == Qt::Key_W) {
        W = "WG";
        sendData(QString(W).toUtf8(),tcpSocket);
        qDebug() << "W键被按下";
    } else if(event->key() == Qt::Key_A) {
        A = "AG";
        sendData(QString(A).toUtf8(),tcpSocket);
        qDebug() << "A键被按下";
    } else if(event->key() == Qt::Key_S) {
        S = "SG";
        sendData(QString(S).toUtf8(),tcpSocket);
        qDebug() << "S键被按下";
    } else if(event->key() == Qt::Key_D) {
        D = "DG";
        sendData(QString(D).toUtf8(),tcpSocket);
        qDebug() << "D键被按下";
        }
    // 处理其他按键
}

void MainWindow::keyReleaseEvent(QKeyEvent *event){
    if(event->isAutoRepeat()) {
        return; // 忽略自动重复的事件
    }

    if(event->key() == Qt::Key_W) {
        W = "WS";
        sendData(QString(W).toUtf8(),tcpSocket);
    } else if(event->key() == Qt::Key_A) {
        A = "AS";
        sendData(QString(A).toUtf8(),tcpSocket);
    } else if(event->key() == Qt::Key_S) {
        S = "SS";
        sendData(QString(S).toUtf8(),tcpSocket);
    } else if(event->key() == Qt::Key_D) {
        D = "DS";
        sendData(QString(D).toUtf8(),tcpSocket);
    }
}

void MainWindow::onTimerTimeout(){

}

void MainWindow::handleSerialError(QSerialPort::SerialPortError error) {

}

void MainWindow::on_SerialButton_2_clicked()
{

}

void MainWindow::on_SpeedcomboBox_activated(const QString &arg1)
{
    sendData(arg1.toUtf8(), tcpSocket);
}

void MainWindow::getLocalIPAddresses() {
    QList<QHostAddress> ipAddressesList;
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();

    // 遍历所有网络接口
    foreach (const QNetworkInterface &interface, interfaces) {
        // 检查接口是否启用且不是回环地址
        if (interface.flags().testFlag(QNetworkInterface::IsUp) && !interface.flags().testFlag(QNetworkInterface::IsLoopBack)) {

            // 获取接口的 IP 地址条目
            QList<QNetworkAddressEntry> addressEntries = interface.addressEntries();
            foreach (const QNetworkAddressEntry &entry, addressEntries) {
            // 筛选 IPv4 地址
                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                ipAddressesList.append(entry.ip());
                }
            }
        }
    }

    // 输出所有获取到的 IPv4 地址
    foreach (const QHostAddress &address, ipAddressesList) {
        qDebug() << "IPv4 Address:" << address.toString();
        ui->SerialPortcomboBox->addItem(address.toString());
    }
}

void MainWindow::newConnection_slot()
{
    qDebug() <<"有客户端申请连接";

    //获取最新连接的客户端套接字
    //[virtual] QTcpSocket *QTcpServer::nextPendingConnection()
    tcpSocket = tcpServer->nextPendingConnection();
    QMessageBox::information(this, "成功", "客户端连接成功");
    ui->label_10->setText("小车已连接");

    //此时，客户端就和服务器建立起来联系了
    //如果客户端有数据向服务器发送过来，那么该套接字就会自动发送一个readyread信号
    //我们可以将该信号连接到自定义的槽函数中处理相关逻辑
    connect(tcpSocket, &QTcpSocket::readyRead, this, &MainWindow::readyRead_slot);
}

void MainWindow::readyRead_slot()
{
    QString text = tcpSocket->readAll();
    ui -> RecvBrowser->append(text);
}
